package com.itstu.config;

import com.itstu.annotaion.LoginUser;
import com.itstu.exception.GlobalException;
import com.itstu.pojo.User;
import com.itstu.utils.JwtUtil;
import com.itstu.utils.StringUtils;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * @Author 梁卓
 * @Version 1.0
 * @ClassName LoginUserHandlerMethodArgumentResolver
 * @Description TODO
 * @Date 2024/09/29 22:40
 */
@Configuration
public class LoginUserHandlerMethodArgumentResolver implements HandlerMethodArgumentResolver {

    @Resource
    private JwtUtil jwtUtil;

    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        return parameter.getParameterType().isAssignableFrom(User.class)
                && parameter.hasParameterAnnotation(LoginUser.class);
    }

    @Override
    public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
        // 从请求头中获取token
        HttpServletRequest request = webRequest.getNativeRequest(HttpServletRequest.class);
        String token = request.getHeader("Authorization");
        if (StringUtils.isEmpty(token)) {
            throw new GlobalException("未登录");
        }
        // token过期  token错误 等就不判断了
        return jwtUtil.getToken(token);
    }
}
